package com.seeingtv.common.utils;

import org.apache.log4j.Logger;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author hubert
 * @date 2017-11-11
 * */
public class SafeUtils {
    private static Logger log =  Logger.getLogger(SafeUtils.class);

    private static String localIPFlag = "";

    private SafeUtils() {
        log.info("工具类SafeUtils");
    }


    /**
     * 判断对象是否可安全转为为整数
     * */
    public static boolean isDia(Object obj){
        if (obj == null || "".equals((""+obj).trim())) {
            return false;
        }
        String s = ""+obj;
        char[] c = s.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i]>'9' || c[i]<'0') {
                return false;
            }
        }
        return true;
    }


    public static String getLocalIPFlag(){
        if (localIPFlag.length()>0) { return localIPFlag; }
        try {
            InetAddress[] inets=InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
            for (int i = 0; i < inets.length; i++) {
                int flag = inets[i].getAddress()[3]<<0  &  0xff ;
                if ( flag>1 ) {
                    localIPFlag="000"+flag;
                    localIPFlag = localIPFlag.substring(localIPFlag.length()-2, localIPFlag.length());
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
        }
        return localIPFlag;
    }

    public static Date getDate(Object obj, String format) {
        Date tmpdate = null;
        if ((format == null) || ("".equals(format))){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sf = new SimpleDateFormat(format);
        if (obj != null) {
            try {
                if (obj.toString().startsWith("1-")) {
                    return tmpdate;
                }
                tmpdate = new java.util.Date(sf.parse(obj.toString().trim()).getTime());
            } catch (Exception ex) {
                log.error("getDate :" + ex.getMessage(),ex);
            }
        }
        return tmpdate;
    }

    public static Date safeGetDate(String dateformat) {
        dateformat = dateformat.replaceAll("[^0-9]", "");
        if (dateformat.replaceAll("[0-9]*", "").length() == 0) {
            if (dateformat.length() == 8) {
                return getDate(dateformat, "yyyyMMdd");
            }
            if (dateformat.length() == 14) {
                return getDate(dateformat, "yyyyMMddHHmmss");
            }
            if (dateformat.length() == 12) {
                return getDate(dateformat, "yyyyMMddHHmm");
            }
            if (dateformat.length() == 6) {
                return getDate(dateformat, "HHmmss");
            }
        }
        return null;
    }

    public static Long getLong(Object obj) {
        return getLong(obj, null);
    }

    public static Long getLong(Object obj, Long defvalue) {
        Long tmpret = defvalue;
        if (obj != null) {
            try {
                if (isDia(obj)) {
                    tmpret = Long.valueOf(obj.toString().trim());
                    return tmpret;
                }
            } catch (Exception ex) {
                log.error(ex.getMessage(),ex);
            }
        }
        return tmpret;
    }

    public static int getInt(Object obj){
        if(obj == null) {
            return 0;
        }
        if ( isDia(obj) ) {
            return Integer.valueOf(obj.toString().trim());
        }
        return 0;
    }

    public static int getInt(Object obj,int defvalue){
        int tmpret =defvalue;
        if(obj!=null){
            try{
                tmpret = Integer.parseInt(obj.toString());
            }catch(Exception ex){
                log.error(ex.getMessage(),ex);
            }
        }
        return tmpret;
    }

    public static String getString(Object obj){
        String tmpret = "";
        if(obj!=null){
            tmpret = obj.toString();
        }
        return tmpret.trim();
    }

    /**
     * 拼接路径，避免出现双斜杠
     * @param preUrl
     * @param nextUrl
     * @return
     */
    public static String getLocalUrl(String preUrl,String nextUrl) {
        String tmpNetworkurl = "";
        preUrl = getString(preUrl);
        nextUrl = getString(nextUrl);
        preUrl = preUrl.replace("\\", "/");
        nextUrl = nextUrl.replace("\\", "/");
        if(!preUrl.endsWith("/")){
            preUrl = preUrl+"/";
        }
        if(nextUrl.startsWith("/")&&nextUrl.length()>1) {
            nextUrl = nextUrl.substring(1);
        }
        tmpNetworkurl = preUrl+nextUrl;

        return tmpNetworkurl;
    }

    public static String[] getSingleMatchValue(String str ) {
        String[] values=null;
        if (str==null) {
            return values;
        }

        String[] strs=str.split("://");
        if (strs==null||strs.length==0) {
            return values;
        }
        if (strs==null||strs.length<2||!strs[0].equalsIgnoreCase("ftp")) {
            return values;
        }
        values=new String[5];
        String address=strs[1].replaceAll("//", "/");
        values[0]=address.substring(0, address.indexOf(':'));
        address=address.substring(address.indexOf(':')+1, address.length());
        String result="";
        String regEx = "@[0-9.:]{4,25}";
        Pattern p = Pattern.compile(regEx);
        Matcher m=p.matcher(address);
        if (m.find()&& m.toMatchResult().group()!=null) {
            result=m.toMatchResult().group().trim();
        }else{
            result="";
        }
        values[1]=address.split(result)[0] ;
        values[4]=address.split(result)[1];
        values[4]=values[4].substring( values[4].indexOf('/')+1);
        values[2]=result.substring( result.indexOf('@')+1);
        if (values[2].contains(":")) {
            String[] temp=values[2].split(":");
            values[2]=temp[0];
            values[3]=temp[1];
        }else{
            values[3]="21";
        }

        return values;
    }

    /**
     * 匹配IPV6 ftp地址
     * @param ftpURL
     * @return
     */
    public static String[] getSingleMatchValue2(String ftpURL ) {
        String [] values = null;
        return values;
    }

    public static String getSqlCurrentTimeStr(String format){
        String tmpret="";
        try {
            Calendar ca           =   Calendar.getInstance();
            SimpleDateFormat   sdf   = new SimpleDateFormat(format);
            tmpret = sdf.format(ca.getTime());
        }catch(Exception ex){
            log.error("getCurrentTimeStr:"+ex,ex);
        }
        return tmpret;
    }


}
